package me.shurufa.widget;

import android.view.View;
import android.widget.AbsListView;

/**
 * ListView GridView 滚动到底部自动加载监听器
 *
 * @FileName: me.shurufa.widget.ViewPageTracker.java
 * @author: kHRYSTAL
 * @email: 723526676@qq.com
 * @date: 2016-01-25 18:52
 */
public class ViewPageTracker implements AbsListView.OnScrollListener {

    private OnPageListener onPageListener = null;

    private int mPage = 1;

    private boolean isPageEnd = false;

    private Object object = new Object();

    public ViewPageTracker(OnPageListener listener) {
        this.onPageListener = listener;
    }

    public void setPageEnd(boolean end) {
        this.isPageEnd = end;
    }

    public void setmPage(int mPage){
        this.mPage = mPage;
    }

    @Override
    public void onScrollStateChanged(AbsListView view, int scrollState) {
    }

    @Override
    public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
        this.onPageListener.onScrollY(getScrollY(view));
        if (view.getLastVisiblePosition() == (view.getCount() - 1)) {
            synchronized (onPageListener) {
                if (!isPageEnd && !this.onPageListener.isRequesting()) {
                    mPage++;
                    this.onPageListener.onPageStart(mPage);
                }
            }
        }
    }

    public int getScrollY(AbsListView listView) {
        View c = listView.getChildAt(0);
        if (c == null) {
            return 0;
        }
        int firstVisiblePosition = listView.getFirstVisiblePosition();
        int top = c.getTop();
        return -top + firstVisiblePosition * c.getHeight();
    }
}
